﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.IO;

using Prism.Games.GalEngine.Scripts.Data.SceneElements;


namespace Prism.Games.GalEngine.Scripts.Parser
{
    public sealed class Cache : Collection<CacheObject>
    {
        public Cache()
            : base()
        {

        }

        public new void Clear()
        {
            foreach (var i in this)
            {
                if (i.Content is BackgroundMusic)
                {
                    Helper.Parser.BgmParser.Restart();
                    Helper.Parser.TrademarkBgmParser.Restart();
                    Helper.Parser.MenuBgmParser.Restart();
                }
                else if (i.Content is Vocal)
                {
                    Helper.Parser.VocalParser.Restart();
                }
                else if (i.Content is SystemSound)
                {
                    Helper.Parser.ESParser.Restart();
                }
                i.Stream.Close();
                i.Content.IsCached = false;
            }
            base.Clear();
        }

        public new void Add(CacheObject item)
        {
            var q = from i in this
                    where i.Content == item.Content
                    select i;
            if (q.Count() == 1)
                return;
            else
                base.Add(item);
        }

        public CacheObject GetItem(Prism.Games.GalEngine.Scripts.FunctionModel.IUriContent content)
        {
            var q = from i in this
                    where i.Content == content
                    select i;
            if (q.Count() == 1)
                return q.Single();
            else return null;
        }

        public bool EnsureItem(Prism.Games.GalEngine.Scripts.FunctionModel.IUriContent content)
        {
            var q = from i in this
                    where i.Content == content
                    select i;
            if (q.Count() == 1)
                return true;
            else return false;
        }
    }

    public class CacheObject
    {
        public Stream Stream { get; set; }

        public Prism.Games.GalEngine.Scripts.FunctionModel.IUriContent Content { get; set; }
    }
}
